import axios from "./axios.js";

var source;

class Http {
  get(url, params) {
    // if (axios) {
    //   source = axios.CancelToken.source(); // 这里初始化source对象
    // }
    let tokenObj = {token: localStorage.getItem("token")};
    return new Promise((resolve, reject) => {
      axios.get(url, {params: Object.assign(tokenObj, params)}).then(response => {
        resolve(response);
      }).catch(error => {
        console.log('请求失败', error);
        reject(error);
      });
    });
  }

  cancel() {
    source.cancel('请求已取消')
  }

  post(url, params, config) {
    if (axios) {
      source = axios.CancelToken.source(); // 这里初始化source对象
    }
    let tokenObj = {token: localStorage.getItem("token")};
    let data = Object.assign(tokenObj, params);
    return new Promise((resolve, reject) => {
      if (config) {
        config.cancelToken = source.token;
      }
      axios.post(url, data).then(response => {
        resolve(response);
      }).catch(error => {
        console.log(error);
        reject(error);
      });
    });
  }

  put(url, params) {
    return new Promise((resolve, reject) => {
      axios.put(url, params).then(response => {
        resolve(response);
      }).catch(error => {
        reject(error);
      })
    })
  }

  patch(url, params) {
    return new Promise((resolve, reject) => {
      axios.patch(url, params).then(response => {
        resolve(response);
      }).catch(error => {
        reject(error);
      })
    })
  }

  delete(url, params) {
    return new Promise((resolve, reject) => {
      axios.delete(url, params).then(response => {
        resolve(response);
      }).catch(error => {
        reject(error);
      });
    })
  }


}

export default new Http();
